//
//  LoginViewController.m
//  CarCare
//
//  Created by ileo on 14-8-11.
//  Copyright (c) 2014年 baozun. All rights reserved.
//

#import "LoginViewController.h"
#import "BaseWebViewController.h"

#import "DriveCodeViewController.h"
#import "MyCarInfoInputViewController.h"
#import "LCLoginViewController.h"
#import "OBDViewController.h"
#import "UserHelper.h"

@interface LoginViewController ()

@property (nonatomic, strong) UIButton *registerButton;

@property (nonatomic, strong) UITextField *telTextField;
@property (nonatomic, strong) UIButton *okButton;
@property (nonatomic, strong) UIButton *codeButton;
@property (nonatomic, strong) UITextField *codeTextField;

@property (nonatomic, strong) UIButton *privacyButton;
@property (nonatomic, strong) UIButton *simulationButton;

@property (nonatomic ,strong) UIButton *callMessageButton;

@property (nonatomic , strong) UILabel * codeButtonOnLabel;

@end

@implementation LoginViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    USERINFO.isLogin = NO;
    [UserHelper visiterDisappearBuyCar];
    self.view.backgroundColor = COLOR_HEXSTRING(@"#F6F6F9");
    self.title = LOCSTRING(@"login");
    __weak __typeof(self) wself = self;
    [self navSetupLeftTitle:@"取消" action:^{
        [wself.view endEditing:YES];
        [wself dismissViewControllerAnimated:YES completion:nil];
    }];
    
    
    // 手机号 和 验证码
    
    self.telTextField = [self textFieldWithFrame:FactoryRectDefault(14) type:TEXTFIELD_TEL];
    [self.telTextField becomeFirstResponder];
    [[[UIView viewWithFrame:CGRectMake(0, self.telTextField.top,__MAIN_WIDTH, 0.5 * __MAIN_RATIO_H_667)] resetBackgroundColor:COLOR_HEXSTRING(@"#DCDCDC")] setupOnView:self.view];
    
    self.telTextField.text = [USERINFO.tel isEqualToString:@"13917103046"] ? @"" : USERINFO.tel;
    self.codeTextField = [self textFieldWithFrame:FactoryRectDefault(self.telTextField.bottom + GAP_HEIGHT) type:TEXTFIELD_CODE];
    [[[UIView viewWithFrame:CGRectMake(22 * __MAIN_RATIO_H_667, self.codeTextField.top, __MAIN_WIDTH - 44 * __MAIN_RATIO_H_667, 0.5 * __MAIN_RATIO_H_667)] resetBackgroundColor:COLOR_HEXSTRING(@"#DCDCDC")] setupOnView:self.view];
    
    [[[UIView viewWithFrame:CGRectMake(0, self.codeTextField.bottom , __MAIN_WIDTH, 0.5 * __MAIN_RATIO_H_667)] resetBackgroundColor:COLOR_HEXSTRING(@"#DCDCDC")] setupOnView:self.view];
    
    
    // 2090E6
    // 登录按钮
    CGFloat okButtonWidth = 330.5 * __MAIN_RATIO_375;
    CGFloat okButtonHeight = 40 * __MAIN_RATIO_H_667;
    self.okButton = [ViewFactory buttonWithFrame:CGRectMake(22 * __MAIN_RATIO_375, self.codeTextField.bottom + 28 * __MAIN_RATIO_H_667,okButtonWidth, okButtonHeight)  title:@"登录" normalColor:COLOR_HEXSTRING(@"#1F90E5") highlightColor:COLOR_HEXSTRING(@"#1F90E5") disabledColor:[Theme wordGrayColor] inView:self.view action:^{
        [wself clickOnOK];
    }];
//    [Factory buttonWithFrame:CGRectMake(22 * __MAIN_RATIO_375, self.codeTextField.bottom + 28 * __MAIN_RATIO_H_667,okButtonWidth, okButtonHeight) bgColor:COLOR_HEXSTRING(@"#1F90E5") title:@"登录" textColor:nil click:^{
//        [wself clickOnOK];
//    } onView:self.view];
//    self.okButton.enabled = ![self allTextFieldTextHasNull];
    self.okButton.clipsToBounds = YES;
    self.okButton.layer.cornerRadius = 2;
    self.okButton.enabled = NO;
    
    
    // 收不到短信验证码
    CGFloat callButtonWidth = 250 * __MAIN_RATIO_375;
    CGFloat callButtonHeight = 14 * __MAIN_RATIO_H_667;
    
    __block UILabel *callMessageLabel = [Factory labelWithFrame:CGRectMake(self.okButton.left, self.okButton.bottom + 18 * __MAIN_RATIO_H_667, callButtonWidth, callButtonHeight) font:FONT_DEFAULT_Light(12) text:@"" textColor:COLOR_HEXSTRING(@"#a4a4a4") onView:self.view textAlignment:NSTextAlignmentLeft];
    
    
    NSString * kongStr = (__MAIN_WIDTH == 320 ? @"":@" ");
    NSString *callMessageStr = [NSString  stringWithFormat:@"收不到短信验证码，%@请点击这里",kongStr];
    NSMutableAttributedString * CMAttributeStr = [[NSMutableAttributedString alloc]initWithString:callMessageStr];
    NSRange CMRange = NSMakeRange([callMessageStr length] - 5, [callMessageStr length] - ([callMessageStr length] - 5));
    [CMAttributeStr addAttribute:NSForegroundColorAttributeName value:COLOR_HEXSTRING(@"#1F90E5") range:CMRange];
    [CMAttributeStr addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:CMRange];
//    [CMAttributeStr addAttribute:NSKernAttributeName value:[NSNumber numberWithInteger: 2 * __MAIN_RATIO_375] range:NSMakeRange(0, [CMAttributeStr length])];
    NSMutableParagraphStyle * CMparegraphStyle = [[NSMutableParagraphStyle alloc]init];
    [CMparegraphStyle  setParagraphSpacing:5];
    [CMAttributeStr addAttribute:NSParagraphStyleAttributeName value:CMparegraphStyle range:CMRange];
    callMessageLabel.attributedText = CMAttributeStr;
    callMessageLabel.hidden = YES;
    
    
    self.callMessageButton = [[UIButton buttonWithFrame:CGRectMake(__MAIN_WIDTH - 22 * __MAIN_RATIO_375 - callButtonWidth, self.okButton.bottom + 18 * __MAIN_RATIO_H_667, callButtonWidth, 30 * __MAIN_RATIO_H_667) title:@"" textColor:COLOR_HEXSTRING(@"#a4a4a4") font:FONT_BUTTON click:^{
        //确认 打电话纪录语音信息  取消  不做处理
        TipsView *tipsV = [TipsView voiceTipsWithTitle:nil lightTitles:@[@"验证码将会以电话方式播报给您，请注意来电，并记下电话中报的验证码"]];
        [tipsV addLeftButton:@"取消" clickLeft:^{
            [AlertMgr dismiss:TYPE_VIEW_ALERT];
        } rightButton:@"获取验证码" clickRight:^{
            [wself callMessageCodeClick];
            [AlertMgr dismiss:TYPE_VIEW_ALERT];
        }];
        [AlertMgr showView:tipsV];
    }] setupOnView:self.view];

    wself.callMessageButton.hidden = YES;
    
    // 隐私及使用协议
    UILabel * privacyLabel = [Factory labelWithFrame:CGRectMake(self.okButton.left, __MAIN_HEIGHT_64 - 109, __MAIN_WIDTH - self.okButton.left * 2, 40) font:[UIFont systemFontOfSize:12] text:@"" textColor:COLOR_HEXSTRING(@"#a4a4a4") onView:self.view textAlignment:NSTextAlignmentCenter];
    
    NSString * privacyStr = [NSString stringWithFormat:@"说明:点击“登录”,表示您已同意%@“隐私及使用协议”",kongStr];
    NSMutableAttributedString * privacyAttributeStr = [[NSMutableAttributedString alloc]initWithString:privacyStr];
    NSRange privacyRange = NSMakeRange([privacyStr length] - 9, [privacyStr length] - ([privacyStr length] - 9));
    [privacyAttributeStr addAttribute:NSForegroundColorAttributeName value:COLOR_HEXSTRING(@"#1F90E5") range:privacyRange];
    [privacyAttributeStr addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:privacyRange];
//    [privacyAttributeStr addAttribute:NSKernAttributeName value:[NSNumber numberWithInteger: 2 * __MAIN_RATIO_375] range:NSMakeRange(0, [privacyAttributeStr length])];
    NSMutableParagraphStyle * paregraphStyle = [[NSMutableParagraphStyle alloc]init];
    [paregraphStyle  setParagraphSpacing:5];
    [privacyAttributeStr addAttribute:NSParagraphStyleAttributeName value:paregraphStyle range:privacyRange];
    privacyLabel.attributedText = privacyAttributeStr;

    // 隐私协议要跳转的界面
    self.privacyButton = [[UIButton buttonWithFrame:CGRectMake(__MAIN_WIDTH - self.okButton.left - __MAIN_WIDTH / 3, __MAIN_HEIGHT_64 - 109, __MAIN_WIDTH / 3, 40) title:@"" textColor:[Theme wordGrayColor] font:FONT_BUTTON click:^{
        BaseWebViewController * webVC = [[[BaseWebViewController alloc]initWithURL:@"http://www.ichezheng.com/agree.html"]navSetupBackItemWithIdentification:BACK_ICON];
        webVC.title = @"使用协议";
        [wself.navigationController pushViewController:webVC animated:YES];
    }] setupOnView:self.view];

    self.privacyButton.titleLabel.textAlignment = NSTextAlignmentLeft;
    
    
    // 验证码
    
    self.codeButton = [ViewFactory addButtonType:BUTTON_CODE onTextField:self.codeTextField inView:self.view action:^{
        [wself.codeTextField becomeFirstResponder];
        wself.simulationButton.top = wself.okButton.bottom + 45 + callMessageLabel.height;
        wself.callMessageButton.hidden = NO;
        callMessageLabel.hidden = NO;
        if ([Check isTel:wself.telTextField.text]) {
            wself.codeButton.enabled = NO;
            [UserHelper getCodeByTel:wself.telTextField.text success:nil fail:^{
                wself.codeButton.enabled = YES;
            }];
        }
    } ok:nil];
    self.codeButtonOnLabel = [Factory labelWithFrame:self.codeButton.frame font:FONT_DEFAULT_Light(14) text:self.codeButton.titleLabel.text textColor:[UIColor grayColor] onView:self.view textAlignment:self.codeButton.titleLabel.textAlignment];
    self.codeButtonOnLabel.hidden = ([self.telTextField.text isTel] ? YES : NO);
    self.codeButton.hidden = ([self.telTextField.text isTel] ? NO : YES);
    
   // 乐成登录
    [[[UIView viewWithFrame:CGRectMake(0,__MAIN_HEIGHT_64 - 45, __MAIN_WIDTH, 45)] resetBackgroundColor:[[UIColor whiteColor] colorWithAlphaComponent:0.8]] setupOnView:self.view];
    
    CGFloat top = __MAIN_HEIGHT_64 - 22.5;
    [Factory flabelWithCenter:CGPointMake(__MAIN_WIDTH/2, top) font:FONT_DEFAULT_Light(13) text:@"乐乘登录" textColor:COLOR_HEXSTRING(@"#1F90E5") onView:self.view resetSizeFinish:^(UILabel *label) {}];
    [[UIButton buttonEmptyWithFrame:CGRectMake(0, 0, 90, 90) click:^{
        LCLoginViewController *vc= [[LCLoginViewController alloc]init];
        
        [wself presentViewController:[UINavigationController navigationControllerWithRootViewController:vc] animated:YES completion:nil willDismissCallback:nil didDismissCallback:^(BOOL success, id info) {
            if (success) {
                [wself loginRequestSuccess];
            }
        }];
    }] setupOnView:self.view].center = CGPointMake(__MAIN_WIDTH/2, top + 20);
    
}
-(void)textFieldTextChanged:(UITextField *)textField
{
    if (textField == self.telTextField) {
        [self.codeButtonOnLabel setHidden:([textField.text isTel] ? YES : NO)];
        [self.codeButton setHidden:([textField.text isTel] ? NO : YES)];
    }
    self.okButton.enabled = (([self.telTextField.text isTel] && [self.codeTextField.text isCode]) ? YES : NO);

}
- (NSInteger)textFieldMaxNumberWithTextField:(UITextField *)textField
{
    if (textField == self.telTextField) {
        return 10;
    }
    else if (textField == self.codeTextField)
    {
        return 5;
    }
    else{
        return [super textFieldMaxNumberWithTextField:textField];
    }
}

- (void)callMessageCodeClick
{
    if ([Check isTel:self.telTextField.text]) {
        
        [UserHelper callMessageCodeByTel: self.telTextField.text success:nil fail:nil];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//-(void)textFieldTextHasNull:(BOOL)null{
//    self.okButton.enabled = !null;
//}

-(void)clickOnKeyBoardDone{
    [self clickOnOK];
}

-(void)clickOnOK{
    
    if([Check isTel:self.telTextField.text] && [Check isCode:self.codeTextField.text]){
        
        __weak __typeof(self) wself = self;
        [self.view endEditing:YES];
        
        [UserHelper loginWithTel:self.telTextField.text code:self.codeTextField.text success:^{
            [wself loginRequestSuccess];
            wself.okButton.enabled = YES;
        } fail:^{
            wself.okButton.enabled = YES;
        }];
    }
}
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}

-(void)loginRequestSuccess{
    USERINFO.isLogin = YES;
    if ([USERINFO.pastDevice isDevice]) {
        if (USERINFO.carStyleID > 0) {
            [SCREEN showMainScreen];
            if (USERINFO.isVisiter) {
                [UserHelper visiterShowBuyCar];
            }
        }else{
            [AlertMgr showView:[self tipsBingdingCar]];
        }
    }else{
        [AlertMgr showView:[self tipsBingdingDevice]];
    }
}
-(TipsView *)tipsBingdingDevice{
    __weak __typeof(self) weakSelf = self;
    TipsView *tipsV = [TipsView textTipsWithTitle:nil lightTitles:@[LOCSTRING(@"tip_bingding_device")]];
    [tipsV addLeftButton:@"下次绑定" clickLeft:^{
        [AlertMgr dismiss:TYPE_VIEW_ALERT];
        [SCREEN showMainScreen];
    } rightButton:@"立即绑定" clickRight:^{
        [weakSelf clickOnBinding];
    }];
    return tipsV;
}

-(TipsView *)tipsBingdingCar{
    __weak __typeof(self) wself = self;
    TipsView *tipsV = [TipsView textTipsWithTitle:nil lightTitles:@[@"请绑定车辆"]];
    [tipsV addLeftButton:@"取消" clickLeft:^{
        [wself clickOnCancel];
    } rightButton:@"绑定" clickRight:^{
        [AlertMgr dismiss:TYPE_VIEW_ALERT];

        MyCarInfoInputViewController *vc = [[MyCarInfoInputViewController alloc] initWithInputType:TYPE_INPUT_TABLEVIEW carModel:nil];
        [vc resetBindingClickDone:^{
            OBDViewController *obd = [[[OBDViewController alloc] init] navSetupBackItemWithIdentification:BACK_ICON_TITLE];
            [vc.navigationController pushViewController:obd animated:YES];
        }];

        [wself.navigationController pushViewController:vc animated:YES];
        
    }];
    return tipsV;
}

-(void)clickOnCancel{
    [AlertMgr dismiss:TYPE_VIEW_ALERT];
}

-(void)clickOnBinding{
    [AlertMgr dismiss:TYPE_VIEW_ALERT];
    [self.navigationController pushViewController:[[[DriveCodeViewController alloc] init] navSetupBackItemWithIdentification:BACK_ICON_TITLE] animated:YES];
}


- (void)dealloc{
    
    
}

@end